//------------------------------------------------------------------------------
//
// ...
// class: ClientReception 
// author: 喵大斯( as3er.net )
// created: 2015/8/27
// copyright (c) 2015 喵大斯( aosnow@yeah.net )
//
//------------------------------------------------------------------------------

/// <reference path='../core/jquery.d.ts'/>
/// <reference path='../core/jquery.extend.d.ts'/>
/// <reference path='../core/page_core.d.ts'/>
/// <reference path='../core/utils.ts'/>
/// <reference path='../core/submitter.d.ts'/>
/// <reference path='../core/pageset.d.ts'/>
/// <reference path='../core/datepicker.d.ts'/>

class ClientReception
{
	/**
	 * 需要绑定预约的接待类型
	 * @type {string}
	 */
	static TYPE_WITH_RESERVE:string = "with_reserve";

	/**
	 * 非预约接待类型
	 * @type {string}
	 */
	static TYPE_WITHOUT_RESERVE:string = "without_reserve";

	//--------------------------------------------------------------------------
	//
	//  Class constructor
	//
	//--------------------------------------------------------------------------

	/**
	 * 客户预约数据显示控制器
	 * @param table 用于显示预约数据的表格 JQuery 对象
	 * @param type 接待的类型（是否绑定预约记录）
	 */
	constructor( table:JQuery, type:string = "with_reserve" )
	{
		this._table = table;
		this._type = type;
		this.initTable();
	}

	//--------------------------------------------------------------------------
	//
	//	Class properties
	//
	//--------------------------------------------------------------------------

	private _table:JQuery;
	private _tableHtml:JQuery;
	private _type:string;

	//----------------------------------------
	// clientKey
	//----------------------------------------

	/** 客户 key */
	public clientKey:string;

	//----------------------------------------
	// receptionKey
	//----------------------------------------

	/** 接待记录 key（当添加新记录时，此值始终为空） */
	public receptionKey:string = "";

	//--------------------------------------------------------------------------
	//
	//	Class methods
	//
	//--------------------------------------------------------------------------

	private initTable():void
	{
		// 显示/隐藏客户预约数据资料
		var title:JQuery = this._table.find( "tr[rel='title']" );
		title.css( "cursor", "pointer" );
		title.click( ()=>
		{
			this.showOrHideDetailed();
		} );

		// 初始阶段将HTML的行节点对象 缓存到变量中
		this._tableHtml = this._table.find( "tr[rel='title'] ~ tr" );
		this._tableHtml.find( "tr[rel='title'] ~ tr" ).remove();// 初始从表格中移除

		// 学员测评情况表单模板
		$( "#tbl_student_temp" ).hide();
		$( "#student_test_recycle" ).hide();

		// 初始化请求列表内容（只请求数据）
		this.update_student( true );
	}

	/**
	 * 重置表单内容
	 */
	public resetHtmlContent():void
	{
		this._table.find( "tr:not(:first)" ).remove();
		this._table.append( this._tableHtml.clone( false ) );

		// 接待表单添加客户跟踪事件绑定
		this._table.find( "#btnAddTracking" ).click( ()=>{this.execTrackingHandler();} );

		update_row_bg( this._table );

		// 日期控件初始化
		var dp:JQuery = this._table.find( "#rep_date" );
		ipt_dater_init( dp );
		dp.val( today() );

		// 填充动态列表（读取数据库）
		this.update_student( false, true );
	}

	// 设置填充或清空接待数据
	public setReception( d )
	{
		if( !empty( d ) )
		{

			this.receptionKey = d.key;
			this.resetHtmlContent();

			$( "#rep_worth" ).val( d.worth );
			$( "#rep_feature" ).val( d.feature );
			$( "#rep_date" ).html( "<span class=\"stress unit hand\" id=\"rdate\">" + d.date + "</span>" );
			$( "#rep_user_box" ).html( "<span class=\"stress unit hand\" id=\"ruser\">" + d.reception_ns + "</span>" );
			$( "#rep_region_box" ).html( "<span class=\"stress unit hand\" id=\"region\">" + d.region_ns + "</span>" );

			// 学员名单
			if( empty( this._student_html ) )
			{
				if( !empty( this._student_jqXHR ) )
				{
					// 正在请求，尚未完成
					this._student_jqXHR.then( ()=>
					{
						this.setStudentTestData( d );
					} );
				}
				else
				{
					// 没有请求，立即发送请求学员列表
					this.update_student( false, true, ()=>{this.setStudentTestData( d );} );
				}
			}
			else
			{
				// 直接设置学员测评数据
				this.setStudentTestData( d );
			}
		}
		else
		{
			this.receptionKey = null;
			this._table.find( "tr:not(:first)" ).remove();
		}
	}

	// 设置更新学员测评数据
	public setStudentTestData( d )
	{
		var data = $.parseJSON( d.student );
		var box:JQuery = $( "#rep_student_box" );

		for( var key in data )
		{
			var v;

			if( data.hasOwnProperty( key ) )
				v = data[ key ];

			// 勾选学员名单
			var li:JQuery = box.find( "ul > li[rel='" + v.key + "']" );
			li.find( ":checkbox" ).prop( "checked", true );

			// 创建测评表单
			this.setNewStudent( v.key );
			this.requestStudentSingleInfo( v.key );

			// 填充测评数据
			var tbl = $( "#" + key );
			this.setStudentData( tbl, v );
		}
	}

	//--------------------------------------------------------------------------
	//
	// 学员测评数据维护
	//
	//--------------------------------------------------------------------------

	public setNewStudent( key:string )
	{
		// 克隆表单
		this.copyStudentTemp( key );

		// 设置学员基本数据
		var tbl:JQuery = $( "#" + key );

		// 学员情况包含学员资料和接待情况（来源于tg_student及tg_reception）
		tbl.attr( "rel", key );
	}

	public requestStudentSingleInfo( key:string )
	{
		$.post( "search_student_single.php", { key: key }, ( d )=>
		{
			this.setStudentInfo( d );
		}, "json" );
	}

	public setStudentInfo( d )
	{
		var tbl = $( "#student_test_list" ).find( "#" + d.key );
		if( !tbl.exist() )tbl = $( "#student_test_recycle" ).find( "#" + d.key );

		if( tbl.exist() )
		{
			var name = defaultVal( d.nickname );
			var sex = defaultVal( d.sex );
			var age = defaultVal( d.age );

			tbl.find( "[rel='btnStudent']" ).attr( "rev", d.key );
			tbl.find( "tr:first th" ).html( "学员 [ " + name + " ] 的测评情况" );
			tbl.find( "[rel='student_info']" ).html( name + "，" + sex + "，" + age + " 岁" );
		}
	}

	public requestStudentInfo( key )
	{
		submitter.post( "student_search.php", { key: key }, ( d )=>
		{
			if( d.err == 0 )
			{
				var size = parseInt( d[ 'size' ] );

				for( var i = 0; i < size; i++ )
				{
					var v = d[ i ];

					// 更新表单中的学员基本资料（姓名，性别，年龄）
					this.setStudentInfo( v );

					// 更新接待表单中学员列表的基本资料（复选框）
					this.updateStudentListInfo( v );
				}
			}
			else
			{
				infopad.err( d.msg );
			}
		}, "json" );
	}

	// 设置指定表单的学员接待数据
	private setStudentData( tbl, d )
	{
		tbl.find( "[rel='testuser'] select" ).val( d.testuser );
		tbl.find( "#price" ).val( d.price );
		tbl.find( "#moneylog" ).val( d.moneylog );
		tbl.find( "#reason" ).val( d.reason );
		tbl.find( "#remark" ).val( d.remark );

		// 设置当前选择的测评完成情况选择
		var selects = ( !empty( d.result ) ? d.result : "" ).split( "," );
		var ps = tbl.find( "[rel='result'] > div" ).find( "p[rel^='TR_']" );

		// 过滤兼容没有选择的旧记录
		if( selects.length == ps.length )
		{
			ps.each( function( id )
			{
				var val = selects[ id ];
				if( val )
				{
					var txt = "";

					if( val.indexOf( ":" ) != -1 )
					{
						var tmp = val.split( ":" );
						val = tmp[ 0 ];
						txt = tmp[ 1 ];
					}

					$( this ).find( ":radio[value=" + val + "]" ).prop( "checked", true );

					if( $( this ).find( "input[name^='TXT_']" ).length > 0 )
						$( this ).find( "input[name^='TXT_']" ).val( txt );
				}
			} );
		}
	}

	private copyStudentTemp( id )
	{
		var temp:JQuery = $( "#tbl_student_temp" );
		var container:JQuery = $( "#student_test_list" );

		container.append( temp.clone( true ) );
		var tbl = container.find( "table:last" );
		tbl.show();
		tbl.attr( "id", id );

		// 学员表单头部点击事件
		tbl.find( "tr:first > th" ).click( this.nameRowClick );
		tbl.find( "tr:first > th" ).css( "cursor", "pointer" );
		tbl.find( "tr:first > th" ).trigger( "click" );

		// 弹出学员资料编辑窗口
		tbl.find( "[rel='btnStudent']" ).click( ( e )=>{this.editStudentHandler( e );} );

		// 测评项目调查表隐藏、显示
		tbl.find( "[rel='btnShowVote']" ).hide();
		tbl.find( "[rel='btnArrow']" ).add( tbl.find( "[rel='btnShowVote']" ) ).click( function()
		{
			var vote = tbl.find( "[rel='result'] > div" );
			if( vote.visible() )
			{
				vote.hide();
				tbl.find( "[rel='btnShowVote']" ).show();
			}
			else
			{
				vote.show();
				tbl.find( "[rel='btnShowVote']" ).hide();
			}
		} );
		tbl.find( "[rel='btnArrow']" ).trigger( "click" );

	}

	// 点击表头时，隐藏表体
	private nameRowClick()
	{
		var tbl = $( this ).parent().parent();
		var show = tbl.find( "tr:not(:first)" ).visible();
		var trs = tbl.find( "tr:not(:first)" );
		show ? trs.hide() : trs.show();
	}

	// 分析返回接待表单数据
	public getFormData():any
	{
		var data:any = {};

		data.client = this.clientKey;
		data.key = this.receptionKey;

		data.rdate = this._table.find( "#rep_date" ).val();
		data.ruser = this._table.find( "#rep_user" ).val();
		data.region = this._table.find( "#rep_region" ).val();
		data.worth = this._table.find( "#rep_worth" ).val();
		data.feature = this._table.find( "#rep_feature" ).val();

		var student:any = {};
		$( "#student_test_list" ).find( " > table" ).each( ( index, el )=>
		{
			var key = $( el ).attr( "id" );
			var data = this.getStudentData( $( el ) );

			// 若返回数据为空，则跳过这个表单
			if( data == false )
				return true;

			student[ key ] = data;
		} );
		data.student = JSON.stringify( student );

		return data;
	}

	/**
	 * 收集格式化指定表单的学员接待数据
	 */
	private getStudentData( tbl ):any
	{
		var data:any = {};
		data.key = tbl.attr( "id" );
		data.testuser = tbl.find( "[rel='testuser'] select" ).val();
		data.price = tbl.find( "#price" ).val();
		data.moneylog = tbl.find( "#moneylog" ).val();
		data.reason = tbl.find( "#reason" ).val();
		data.remark = tbl.find( "#remark" ).val();

		// 若测评老师未选择则视为无效记录
		if( empty( data.testuser )
			&& empty( data.price )
			&& empty( data.moneylog )
			&& empty( data.reason )
			&& empty( data.remark ) )
			return false;

		// 测评完成情况选择列表
		var selects = [];
		tbl.find( "[rel='result'] > div" ).find( "p[rel^='TR_']" ).each( function()
		{
			var name = $( this ).attr( "rel" );
			var ns:Array<string> = name.split( "_" );
			var id:any = ns[ 1 ];
			var val = $( this ).find( ":radio:checked" ).val();
			var remark = $( this ).find( "input[name='TXT_" + id + "']" ).val();

			if( typeof ( val ) == 'undefined' )
			{
				//infopad.err( "测评完成情况第 " + name.replace( "TR_", "" ) + " 条未选择。" );
				val = 0;
			}

			if( !empty( remark ) )
			{
				remark = remark.replace( /,/ig, "，" );// 英文逗号换成中文的，以免打乱数据分隔符
				val = val + ":" + remark;
			}

			// 选择值：1-是，2-否，0-未选择
			selects.push( val );
		} );
		data.result = selects.join( "," );

		return data;
	}

	//--------------------------------------------------------------------------
	//
	//  数据列表刷新方法
	//
	//--------------------------------------------------------------------------

	private _student_html:string;
	private _student_jqXHR:JQueryXHR;

	// 刷新当前表单的学员列表
	private update_student( onlyRequest:boolean = false, onlySet:boolean = false, callback?:Function )
	{
		var box:JQuery = this._table.find( "#rep_student_box" );

		if( onlySet && !empty( this._student_html ) )
		{
			box.html( this._student_html );
		}
		else
		{
			var back:Function = ( d )=>
			{
				// 返回结果，重置 XHR，不论是否正确结果
				this._student_jqXHR = null;

				if( d.err == 0 )
				{
					var size = parseInt( d[ 'size' ] );
					var html:string = "";

					for( var i = 0; i < size; i++ )
					{
						var v = d[ i ];
						var info = v.nickname + '， ' + v.sex + '， ' + v.age + ' 岁';
						html += `<li rel='${v.key}' class='stress rect' style='list-style:none;float:left;width:200px;margin:2px;'>
								<label><input type='checkbox' rel='${v.key}'><span>${info}</span></label>
							</li>`;
					}

					var isDataEmpty:boolean = empty( html );

					if( isDataEmpty )
					{
						html = `<em class="caption" style="color:#ff3300;">（客户名下无登记学员）</em>`;
					}
					else
					{
						html = `<ul id='rep_student'>${html}</ul>`;
					}

					if( !onlyRequest )
					{
						box.html( html );
					}

					if( !isDataEmpty ) this._student_html = html;
					if( $.isFunction( callback ) && !isDataEmpty )callback( html );

					// 弹出学员资料编辑窗口
					box.find( ":checkbox" ).change( { cls: this }, this.studentSelectHandler );
				}
				else
				{
					infopad.err( d.msg );
				}
			};

			// 若当前已经存在未结束的请求，则中断请求
			if( !empty( this._student_jqXHR ) ) this._student_jqXHR.abort();

			// 发送新的请求
			this._student_jqXHR = submitter.post( "student_search.php", { key: this.clientKey }, back, "json" );
		}
	}

	// 刷新当前表单的单个学员资料
	private updateStudentListInfo( d )
	{
		var box:JQuery = $( "#rep_student_box" );
		var li:JQuery = box.find( "ul > li[rel='" + d.key + "']" );

		var name = defaultVal( d.nickname );
		var sex = defaultVal( d.sex );
		var age = defaultVal( d.age );
		var info = name + "，" + sex + "，" + age + " 岁";

		if( !li.exist() )
		{
			var html = `<li rel='${d.key}' class='stress rect' style='list-style:none;float:left;width:200px;margin:2px;'>
							<label><input type='checkbox' rel='${d.key}'><span>${info}</span></label>
						</li>`;
			box.find( "ul" ).append( html );
		}
		else
		{
			li.find( "label span" ).html( info );
		}
	}

	//--------------------------------------------------------------------------
	//
	//  Event handlers
	//
	//--------------------------------------------------------------------------

	private showOrHideDetailed():void
	{
		var trs = this._table.find( "tr[rel='title'] ~ tr" );
		var show = trs.eq( 0 ).visible();
		show ? trs.hide() : trs.show();
	}

	// 当学员目标被选择或取消时
	private studentSelectHandler( e ):void
	{
		var checked:boolean = $( this ).prop( "checked" );
		var key:string = $( this ).attr( "rel" );
		var tbl:JQuery = $( "#student_test_list" );
		var tmpTbl:JQuery = $( "#student_test_recycle" );

		if( checked )
		{
			// 显示到测评学员列表
			var temp:JQuery = tmpTbl.find( "#" + key );
			if( temp.exist() )
			{
				tbl.append( temp );

				// 从回收站拿回来的表单，默认隐藏内容
				tbl.find( "#" + key ).find( "tr:not(:first)" ).hide();
			}
			else
			{
				e.data.cls.setNewStudent( key );
				e.data.cls.requestStudentSingleInfo( key );
			}
		}
		else
		{
			// 从列表移除到回收站容器，便于在恢复时能保留之前填写的数据
			var table:JQuery = tbl.find( "#" + key );
			if( table.exist() )
			{
				tmpTbl.append( table );
			}
		}
	}

	private editStudentHandler( e )
	{
		if( empty( this.clientKey ) )
		{
			infopad.err( "请先指定目标客户，再编辑学员资料。" );
			return;
		}

		var studentKey = $.trim( $( e.currentTarget ).attr( "rev" ) );
		var url = "consultant_student.php?pkey=" + this.clientKey + "&student=" + studentKey + "&close=true";
		var title = "编辑学员资料";
		var id = "consultant_student_" + this.clientKey + "_" + studentKey;

		create_model( url, title, id, null, ()=>{this.editStudentCloseHandler();} );
		open_model( id, true );
	}

	private execTrackingHandler()
	{
		if( empty( this.clientKey ) )
		{
			infopad.err( "请先指定目标客户，再添加跟踪情况。" );
			return;
		}

		var url = "consultant_client_tracking.php?key=" + this.clientKey;
		var title = "追加跟踪记录";
		var id = "consultant_client_tracking";

		create_model( url, title, id, 8999 );
		open_model( id, true );
	}

	private editStudentCloseHandler()
	{
		// 刷新学员资料
		if( this.clientKey != null )
		{
			this.requestStudentInfo( this.clientKey );
		}
	}
}

function defaultVal( val ):string
{
	if( empty( val ) )
		return "-";
	return val;
}